import redis
import json
from datetime import datetime
from typing import Union


from util.log import Log
from common.config.ReadConfig import REDIS_CONFIG

redis_client = redis.Redis(**REDIS_CONFIG)

class DateTimeEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime):
            return o.isoformat()
        return super().default(o)

class Redis:
    # time: seconds
    @staticmethod
    def setItem(key: str, value: dict, time: int = None):
        try:
            if time == None or time <= 0:
                redis_client.set(name=key, value=json.dumps(value, cls=DateTimeEncoder))
            else:
                redis_client.setex(name=key, value=json.dumps(value, cls=DateTimeEncoder), time=time)
        except Exception as e:
            Log.error('Redis setItem 异常', e)
            raise e

    @staticmethod
    def getItem(key: str) -> Union[dict, None]:
        try:
            obj = redis_client.get(key)
            if obj == None:
                return None
            else:
                return json.loads(obj)
        except Exception as e:
            Log.error('Redis getItem 异常', e)
            raise e

    @staticmethod
    def deleteItem(key: str):
        try:
            return redis_client.delete(key)
        except Exception as e:
            Log.error('Redis deleteItem 异常', e)
            raise e
